package com.easpeed.comon.utils

/**
 * Created by bigyu on 2025-01-24 14:13
 * com.easpeed.comon.utils
 */
import com.google.gson.Gson
import okhttp3.*
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import java.io.File
import java.io.IOException
import java.util.concurrent.TimeUnit

object OkHttpHelper {

    // 创建 OkHttpClient 实例
    private val client: OkHttpClient = OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS) // 连接超时
        .readTimeout(10, TimeUnit.SECONDS)    // 读取超时
        .writeTimeout(10, TimeUnit.SECONDS)   // 写入超时
        .build()

    /**
     * GET 请求
     * @param url 请求的 URL
     * @param headers 可选请求头
     * @param callback 回调
     */
//    fun get(
//        url: String,
//        headers: Map<String, String>? = null,
//        callback: (success: Boolean, response: String?) -> Unit,
//    ) {
//        val requestBuilder = Request.Builder().url(url)
//
//        // 添加请求头
//        headers?.forEach { (key, value) ->
//            requestBuilder.addHeader(key, value)
//        }
//
//        val request = requestBuilder.build()
//
//        client.newCall(request).enqueue(object : Callback {
//            override fun onFailure(call: Call, e: IOException) {
//                callback(false, e.message)
//            }
//
//            override fun onResponse(call: Call, response: Response) {
//                val responseBody = response.body?.string()
//                callback(response.isSuccessful, responseBody)
//            }
//        })
//    }

    fun get(
        url: String,
        params: Map<String, Any?>? = null, // 新增参数
        headers: Map<String, String>? = null,
        callback: (success: Boolean, response: String?) -> Unit,
    ) {
        // 构建带参数的完整 URL
        val fullUrl = if (!params.isNullOrEmpty()) {
            val httpUrlBuilder = url.toHttpUrlOrNull()?.newBuilder()
            params.forEach { (key, value) ->
                httpUrlBuilder?.addQueryParameter(key, value.toString())
            }
            httpUrlBuilder?.build().toString()
        } else {
            url
        }
        com.bigyu.utils.Logger.e("net-请求参数", " $fullUrl")

        val requestBuilder = Request.Builder().url(fullUrl)
        val newHeaders = HashMap<String, String>()
        if (headers != null) {
            newHeaders.putAll(headers)
        }
        val token = CacheHelper.instance().getStringValue("token")
        if (token != null) {
            newHeaders["token"] = token
        }
        com.bigyu.utils.Logger.e("net-请求头", "$newHeaders")
        // 添加请求头
        newHeaders.forEach { (key, value) ->
            requestBuilder.addHeader(key, value)
        }

        val request = requestBuilder.build()

        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                callback(false, e.message)
                com.bigyu.utils.Logger.e("net-返回结果", " ${e.message}")

            }

            override fun onResponse(call: Call, response: Response) {
                val responseBody = response.body?.string()
                callback(response.isSuccessful, responseBody)
                com.bigyu.utils.Logger.e("net-返回结果", " $responseBody")
            }
        })
    }


    val gson = Gson() // Gson 实例，可放到全局或单例里

    fun post(
        url: String,
        params: Map<String, String> = emptyMap(),
        headers: HashMap<String, String>? = null,
        body: Map<String, Any?>? = null, // 支持 Map 类型 JSON body
        callback: (success: Boolean, response: String?) -> Unit,
    ) {
        val requestBody: RequestBody = if (body != null) {
            val jsonBody = gson.toJson(body)
            com.bigyu.utils.Logger.e("net-请求参数", " $url  \n $jsonBody")
            RequestBody.create("application/json; charset=utf-8".toMediaType(), jsonBody)
        } else {
            val formBodyBuilder = FormBody.Builder()
            params.forEach { (key, value) ->
                formBodyBuilder.add(key, value)
            }
            formBodyBuilder.build()
        }
        val newHeaders = HashMap<String, String>()
        if (headers != null) {
            newHeaders.putAll(headers)
        }
        val token = CacheHelper.instance().getStringValue("token")
        if (token != null) {
            newHeaders["token"] = token
        }
        com.bigyu.utils.Logger.e("net-请求头", "$newHeaders")

        val requestBuilder = Request.Builder()
            .url(url)
            .post(requestBody)

        newHeaders.forEach { (key, value) ->
            requestBuilder.addHeader(key, value)
        }

        val request = requestBuilder.build()

        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                callback(false, e.message)
                com.bigyu.utils.Logger.e("net-返回结果", " ${e.message}")
            }

            override fun onResponse(call: Call, response: Response) {
                val responseBody = response.body?.string()
                com.bigyu.utils.Logger.e("net-返回结果", " $responseBody")
                callback(response.isSuccessful, responseBody)
            }
        })
    }

    fun uploadFile(
        url: String,
        file: File,
        type: String,
        params: Map<String, String> = emptyMap(),
        headers: HashMap<String, String>? = null,
        callback: (success: Boolean, response: String?) -> Unit,
    ) {

        com.bigyu.utils.Logger.e("TAG", "uploadFile: ${file.absolutePath}  ${file.length()}  ${file.length() / 1024 / 1024}MB  ${file.exists()}")

        // Ensure mimeType is detected properly or fallback to application/octet-stream
//        val fileMimeType = URLConnection.guessContentTypeFromName(file.name)
            ?: "application/octet-stream"
//        val requestFile = file.asRequestBody(fileMimeType.toMediaTypeOrNull())

        // Initialize MultipartBody.Builder
        val builder = MultipartBody
            .Builder()
            .setType(MultipartBody.FORM)

        // Add the file part
//        builder.addFormDataPart("file", file.name, requestFile)

        // Add the type parameter
//        builder.addFormDataPart("type", type)
        val requestFile = RequestBody.create("image/jpeg".toMediaTypeOrNull(), file)
        val body = MultipartBody.Part.createFormData("file", "1.jpg", requestFile)
//        builder.addPart(MultipartBody.Part.createFormData("type", "1"))
        builder.addPart(body)

        // Build the request body
        val requestBody = builder.build()

        // Prepare headers
        val allHeaders = mutableMapOf<String, String>()
        headers?.let { allHeaders.putAll(it) }

        // Adding token if present
        val token = CacheHelper.instance().getStringValue("token")
        if (!token.isNullOrEmpty()) {
            allHeaders["token"] = token
        }

        // Log headers for debugging
        com.bigyu.utils.Logger.e("请求头", "$allHeaders")
        com.bigyu.utils.Logger.e("上传文件", "url=$url, file=${file.name}, type=$type")

        // Prepare the request
        val requestBuilder = Request.Builder()
            .url(url)
            .post(requestBody)  // Post the built request body

        // Add headers to the request
        allHeaders.forEach { (key, value) ->
            requestBuilder.addHeader(key, value)
        }

        // Build the final request
        val request = requestBuilder.build()

        // Make the async request
        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                callback(false, e.message)
                com.bigyu.utils.Logger.e("上传失败", e.message ?: "unknown error")
            }

            override fun onResponse(call: Call, response: Response) {
                val responseBody = response.body?.string()
                com.bigyu.utils.Logger.e("上传成功", "$responseBody")
                callback(response.isSuccessful, responseBody)
            }
        })
    }


}
